from django.shortcuts import render,HttpResponse,redirect

from userInfo.models import User
from userInfo.forms import UserForm,RegisterForm
import random,string,os
from django.conf import settings
import json

# Create your views here.
#登录处理
def login(request):
    if request.method == 'GET':
        userform = UserForm()
        return render(request,'userInfo/login.html',locals())
    else:
        userform = UserForm(request.POST)
        if userform.is_valid():
            loginData = userform.cleaned_data
            if User.objects.filter(uname=loginData.get('uname'),upwd=loginData.get('upwd')):
                return HttpResponse('登录成功')
            else:
                return HttpResponse('登录失败')
        else:
            return render(request,'userInfo/login.html',locals())

#注册处理
def register(request):
    if request.method == 'GET':
        regform = RegisterForm()
        return render(request,'userInfo/register.html',locals())
    else:
        regform = RegisterForm(request.POST,request.FILES)  #生成组件验证对象
        print(request.POST)      #110
        print(request.FILES)      #110
        if regform.is_valid():
            regdata = regform.cleaned_data  #验证后的所有数据
            print(regdata)

            # 处理保存图片
            uimg = regdata.get('uimg')
            uimg_name_url = request.session.get('uimg','')
            if not uimg_name_url:
                random_name =  ''.join(random.choices(string.ascii_letters + string.digits,k=10)) + '_'+ uimg.name  #随机名称
                uimg_name_url = os.path.join(settings.STATICFILES_DIRS[1],random_name)
                print(uimg_name_url)    #110
                write_to_file(uimg_name_url, uimg)
                request.session['uimg'] = uimg_name_url = '/static/'+random_name

            #保存注册记录
            print(regdata)  # 110
            datadict = {
                'uname': regdata.get('uname'),
                'upwd' :regdata.get('upwd'),
                'ulev' :int(regdata.get('ulev').strip()),
                'utel' :regdata.get('utel'),
                'uaddr': regdata.get('uaddr'),
                'uimg' :uimg_name_url,
            }
            User.objects.create(**datadict)
            print(datadict)     #110保存的数据字典
            return redirect('/userinfo/login/')
        else:
            return render(request,'userInfo/register.html',locals())

def write_to_file(uimg_name_url,uimg):#保存路径,文件对象
    print(uimg_name_url)  # 110
    with open(uimg_name_url, 'wb') as fw:
        for line in uimg.chunks():
            fw.write(line)

#异步 上传图片返回图片路径
def ajax1_getImgUrl(request):
    uimg = request.FILES.get('file')
    # print(dir(file))

    random_name = ''.join(random.choices(string.ascii_letters + string.digits, k=10)) + '_' + uimg.name     #随机名字
    uimg_name_url = os.path.join(settings.STATICFILES_DIRS[1],random_name)

    print(uimg_name_url)  # 110
    write_to_file(uimg_name_url, uimg)     #保存文件
    server_request_url = '/static/'+random_name

    request.session['uimg'] = server_request_url        #将图片保存到session中

    return HttpResponse(json.dumps(server_request_url))




    # return render(request,'userInfo/register.html',locals())